# -*- coding=utf-8
# appid 已在配置中移除,请在参数 Bucket 中带上 appid。Bucket 由 BucketName-APPID 组成
# 1. 设置用户配置, 包括 secretId，secretKey 以及 Region
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
import time
from django.http import JsonResponse


logging.basicConfig(level=logging.INFO, stream=sys.stdout)

secret_id = 'AKIDHI3cu67d4i6C3PzKwuc7MMhlZ6N6vw0O'  # 替换为用户的 secretId
secret_key = 'BBvPjmZ8VdZFfspVv97tOdcNyIRK3Vhi'  # 替换为用户的 secretKey
region = 'ap-beijing'  # 替换为用户的 Region

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
# 2. 获取客户端对象
client = CosS3Client(config)

response = client.list_buckets(
)

# 参照下文的描述。或者参照 Demo 程序，详见 https://github.com/tencentyun/cos-python-sdk-v5/blob/master/qcloud_cos/demo.py

# response = client.upload_file(  本地的文件上传
#     Bucket='yang-1302094470',
#     LocalFilePath='code.png',
#     Key='p1.png',
'''
response = client.upload_file_from_buffer(    文件对象上传
        Bucket='{0}-1302094470'.format(Bucket),  # request.obj.0.0
        Body=img_path,  # img_object = request.EILES.get('editormd-image-file') 要上传的文件对象
        Key= key

    )

'''
# ============================  上传图片 =============================

def upload(request_obj, img_path, img_key):  # 需要三个参数  一个是当前文档的的id = request.GET.get('wiki_id')  一个是图片的路径 file= request.FILSE.get('editormd-image-file'),img_key=request.FILSE.name
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
    secret_id = 'AKIDHI3cu67d4i6C3PzKwuc7MMhlZ6N6vw0O'  # 替换为用户的 secretId
    secret_key = 'BBvPjmZ8VdZFfspVv97tOdcNyIRK3Vhi'  # 替换为用户的 secretKey
    region = 'ap-beijing'  # 替换为用户的 Region
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    # 2. 获取客户端对象
    client = CosS3Client(config)
    Bucket = '{0}-1302094470'.format(request_obj)
    response = client.list_buckets()  # 这个是获取全部桶的信息
    # 查看用户是否有桶

    # 做的存储的操作
    ext = img_key.rsplit('.')[-1]
    timer = time.time()
    key = "{0}.{1}".format(str(timer), ext)
    # keys = '1.png'
    response = client.upload_file_from_buffer(
        Bucket='{0}'.format(Bucket),  # request.obj.0.0
        Body=img_path,  # img_object = request.EILES.get('editormd-image-file') 要上传的文件对象
        Key=key

    )

    response = client.list_objects(
        Bucket='{0}'.format(Bucket),
        Prefix=''
    )

    image_url = 'https://{0}.cos.{1}.myqcloud.com/{2}'.format(Bucket, region, key)
    return image_url


# 最后得给markdown做一个成功显示的信息
"""
    result = {
        'success': 1,
        'message': None,
        'url': image_url
    }
"""

# =========================  删除 =================================
def delete_file(bucket, key):
    """

    :param bucket: 桶的名字    8-1302094470
    :param key:   图片的名字   1590498110.92144.png
    :return: None
    """
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    client.delete_object(
        Bucket=bucket,
        Key=key
    )


from sts.sts import Sts
from s28 import settings
# ======================== 临时凭证 ===============================
def cos_credentialss(bucket,region):
    """获取cos上传临时凭证"""
    config = {
        'duration_seconds': 1800,
        'secret_id': settings.cos_secret_id,
        'secret_key': settings.cos_secret_key,
        'bucket': bucket,
        'region': region,
        'allow_prefix': '*',
        'allow_actions': [
            '*'
        ],
    }

    sts = Sts(config)
    result_dict = sts.get_credential()

    return result_dict


def delete_bucket(bucket, region):
    """删除桶"""
    # 删除桶中的所有文件
    # 删除桶中的所有碎片
    # 删除桶
    config = CosConfig(Region=region, SecretId=settings.cos_secret_id, SecretKey=settings.cos_secret_key)
    client = CosS3Client(config)
    # 找到所有文件

    try:
        while True:
            part_object = client.list_objects(bucket)
            contents = part_object.get('Contents')
            if not contents:
                break
            objects = {
                'Quiet': 'true',
                'Object':[{'Key':item['Key']} for item in contents]
            }
            client.delete_objects(bucket, objects)

            if part_object['IsTruncated'] == 'false':
                break
        while True:
            part_upload = client.list_multipart_uploads(bucket)
            uploads = part_upload.get('Upload')
            if not uploads:
                break
            for  i in uploads:
                client.abort_multipart_upload(bucket, i['Key'], i['UploadId'])
            if part_upload['IsTruncated'] == 'false':
                break

        client.delete_bucket(bucket)
    except Exception as e:
        pass